package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    //SpringMVC里面的一个类,可以通过这个类来获取到所有的贴有RequestMapping的方法
    @Autowired
    private RequestMappingHandlerMapping rmhm;

    public int insert(Permission record) {
        return permissionMapper.insert(record);
    }

    public int updateByPrimaryKey(Permission record) {
        return permissionMapper.updateByPrimaryKey(record);
    }

    public List<Permission> selectAll() {
        return permissionMapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int total = permissionMapper.query4Count(qo);
        if (total > 0) {
            return new PageResult(total, permissionMapper.query4List(qo));
        }
        return new PageResult(total, Collections.EMPTY_LIST);
    }

    public int deleteByPrimaryKey(Long id) {
        return permissionMapper.deleteByPrimaryKey(id);
    }

    public List<Permission> getPermissionByRoleId(Long roleId) {
        return permissionMapper.getPermissionByRoleId(roleId);
    }

    public void loadPermission() {
        List<String> allResource = permissionMapper.getAllResource();
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = rmhm.getHandlerMethods();
        Collection<HandlerMethod> methods = handlerMethods.values();
        for (HandlerMethod method : methods) {
            RequiresPermissions annotation = method.getMethodAnnotation(RequiresPermissions.class);
            if (annotation != null) {
                String[] value = annotation.value();
                String resource = value[0];
                String name = value[1];
                if (!allResource.contains(resource)) {
                    Permission permission = new Permission();
                    permission.setName(name);
                    permission.setResource(resource);
                    permissionMapper.insert(permission);
                }
            }
        }
    }

    public List<String> getPermissionByEmployeeId(Long employeeId) {
        return permissionMapper.getPermissionByEmployeeId(employeeId);
    }
}
